http
Go supports web application development by default
“net/http” package contains http support.
Handle, HandleFunc
To receive and handle http request, http has 2 methods
Handle : Take ServeHTTP implement
HandleFunc : Take support method
Anyway, it’s better to take a look codes
Sample
|- web | |- getstartedweb.go |- main.go
getstartedweb.go
Create struct and implement ServeHTTP methods under struct
package web import "net/http" type StartHandler struct { Message string } func (f *StartHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) { w.Write([]byte(f.Message)) }
ServeHTTP has ResponseWriter, and Request.
Create StartHandler with message.
StartHandler is public to out side
main.go
Create StartHandler under web package.
Import this and use it.
Also at the same time, we will use HandleFunc
package main import ( "fmt" "net/http" "github.com/DJ110/gorefs/web" ) func main() { http.Handle("/main", &(web.StartHandler{Message: "Hello Web"})) webfunc := func(w http.ResponseWriter, _ *http.Request) { w.Write([]byte("Hello Web2")) } http.HandleFunc("/main2", webfunc) err := http.ListenAndServe(":8080", nil) if err != nil { log.Fatal(err) } }
There are 2 endpoint, /main and /main2
Handle uses ServeHTTP implement pointer, HandleFunc takes function.
ListenAndServe starts golang server with 8080 port.
コメント