HTTP服务

1
2
3
4
5
6
7
8
9
10
11
12
13
14
package main

import (
"net/http"
"fmt"
"log"
)

func main() {
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request){
fmt.Fprint(w, "Hello world")
})
log.Fatal(http.ListenAndServe(":5001", nil))
}

HTTPS服务

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
package main

import (
"log"
"net/http"
)

func handler(w http.ResponseWriter, req *http.Request) {
w.Header().Set("Content-Type", "text/plain")
w.Write([]byte("This is an example server.\n"))
}

func main() {
http.HandleFunc("/", handler)
log.Printf("About to listen on 10443. Go to https://127.0.0.1:10443/")
// One can use generate_cert.go in crypto/tls to generate cert.pem and key.pem.
// ListenAndServeTLS always returns a non-nil error.
err := http.ListenAndServeTLS(":10443", "cert.pem", "key.pem", nil)
log.Fatal(err)
}