Refer to go Web programming, very simple program:
The approximate steps:
-
- Binding IP and Ports
- Bind the corresponding processor or processor function, there are two options, select one to listen to IP and port
- Processor:
- Define a struct structure body
- Then let the struct implement the Servehttp interface.
- Create an instance of the struct
- Pass the instance's address (pointer) as a parameter to the handle
- Processor functions
- Define a function
- The function must be signed with the same function as Servehttp
- Function names are passed directly as parameters to Handlefunc
- Access the bound IP plus port
using the processor form:
Package Mainimport ("FMT" "net/http") type Home struct{}type about Struct{}func (H *home) servehttp (w http. Responsewriter, R *http. Request) {fmt. fprintf (W, "This Is Home")}func (a *about) servehttp (w http. Responsewriter, R *http. Request) {fmt. fprintf (W, "This was about")}func main () {server: = http. SERVER{ADDR: "127.0.0.1:8080",}home: = &home{}about: = &about{}http. Handle ("Home") http. Handle ("/about", about) server. Listenandserve ()}
using the Processor function form:
Package Mainimport ("FMT" "Net/http") Func Home (w http. Responsewriter, R *http. Request) {fmt. fprintf (W, "This was Home2")}func about (w http. Responsewriter, R *http. Request) {fmt. fprintf (W, "This is About2")}func Main () {server: = http. SERVER{ADDR: "127.0.0.1:8080",}http. Handlefunc ("Home") http. Handlefunc ("/about", about) server. Listenandserve ()}
My first go web app to commemorate a moment