Golang : HTTP Server Example
Simple tutorial on HTTP server examples with Golang. Run the codes below and point your browser to http://localhost:8080
or http://localhost:8080/replyname/yourname
for example 2.
Example 1:
package main
import (
"net/http"
)
func SayHelloWorld(w http.ResponseWriter, r *http.Request) {
html := "Hello"
html = html + " World"
w.Write([]byte(html))
}
func main() {
mux := http.NewServeMux()
mux.HandleFunc("/", SayHelloWorld)
http.ListenAndServe(":8080", mux)
}
Example 2:
package main
import (
"net/http"
"strings"
)
func SayHelloWorld(w http.ResponseWriter, r *http.Request) {
w.Write([]byte("Hello, World!"))
}
func ReplyName(w http.ResponseWriter, r *http.Request) {
URISegments := strings.Split(r.URL.Path, "/")
w.Write([]byte(URISegments[1]))
}
func main() {
// http.Handler
mux := http.NewServeMux()
mux.HandleFunc("/", SayHelloWorld)
mux.HandleFunc("/replyname", ReplyName)
http.ListenAndServe(":8080", mux)
}
By Adam Ng
IF you gain some knowledge or the information here solved your programming problem. Please consider donating to the less fortunate or some charities that you like. Apart from donation, planting trees, volunteering or reducing your carbon footprint will be great too.
Advertisement
Tutorials
+35k Golang : Integer is between a range
+25.7k Mac/Linux and Golang : Fix bind: address already in use error
+9.2k Mac OSX : Get a process/daemon status information
+15.2k Golang : Intercept Ctrl-C interrupt or kill signal and determine the signal type
+15.9k Golang : How to extract links from web page ?
+8.2k Golang : Add text to image and get OpenCV's X, Y co-ordinates example
+9.1k Golang : Detect Pascal, Kebab, Screaming Snake and Camel cases
+7.1k Golang : Individual and total number of words counter example
+35k Golang : Strip slashes from string example
+8.8k Golang : Serving HTTP and Websocket from different ports in a program example
+12k Golang : How to display image file or expose CSS, JS files from localhost?