- Building RESTful Web services with Go
- Naren Yellavula
- 208字
- 2021-07-02 20:14:07
Understanding Go's net/http package
Go's net/http package deals with HTTP client and server implementations. Here, we are mainly interested in the server implementation. Let us create a small Go program called basicHandler.go that defines the route and a function handler:
package main
import (
"io"
"net/http"
"log"
)
// hello world, the web server
func MyServer(w http.ResponseWriter, req *http.Request) {
io.WriteString(w, "hello, world!\n")
}
func main() {
http.HandleFunc("/hello", MyServer)
log.Fatal(http.ListenAndServe(":8000", nil))
}
This code does the following things:
- Create a route called /hello.
- Create a handler called MyServer.
- Whenever the request comes on the route (/hello), the handler function will be executed.
- Write hello, world to the response.
- Start the server on port 8000. ListenAndServe returns error if something goes wrong. So log it using log.Fatal.
- The http package has a function called HandleFunc, using which we can map an URL to a function.
- Here, w is a response writer. A ResponseWriter interface is used by an HTTP handler to construct an HTTP response.
- req is a request object, which deals with all the properties and methods of an HTTP request.
Use the log function to debug potential errors. The ListenAndServe function returns an error if there are any.
推薦閱讀
- 光網(wǎng)絡(luò)評估及案例分析
- Force.com Development Blueprints
- 萬物互聯(lián):蜂窩物聯(lián)網(wǎng)組網(wǎng)技術(shù)詳解
- Building RESTful Web Services with Spring 5(Second Edition)
- 城域網(wǎng)與廣域網(wǎng)(第2版)
- 5G技術(shù)與標準
- 高級網(wǎng)絡(luò)技術(shù)
- 深入理解Nginx:模塊開發(fā)與架構(gòu)解析
- 局域網(wǎng)組成實踐
- 組網(wǎng)技術(shù)與網(wǎng)絡(luò)管理
- React Design Patterns and Best Practices(Second Edition)
- Migrating to Drupal7
- 互聯(lián)網(wǎng)戰(zhàn)略變革與未來
- XSS跨站腳本攻擊剖析與防御
- 智能家庭網(wǎng)絡(luò):技術(shù)、標準與應(yīng)用實踐