Golang : Listen and Serve on sub domain example
At this moment, Golang's ListenAndServer()
is able to handle URL with such pattern
www.example.com/api
However, if you try to use ListenAndServe()
function sub domain URL on ... let say for example, api.example.com
such as
package main
import (
"fmt"
"net/http"
)
func handler(w http.ResponseWriter, r *http.Request) {
w.Write([]byte("Hello, World!"))
}
func main() {
http.HandleFunc("/", handler)
fmt.Println(http.ListenAndServe("api.example.com:8080/", nil)) //<-- program will terminate with error
}
the program will terminate with the error message listen tcp: unknown port tcp/8080/
.
So, what's going on ? From the official documentation ServeMux :
Patterns may optionally begin with a host name, restricting matches to URLs on that host only. Host-specific patterns take precedence over general patterns, so
that a handler might register for the two patterns "/codesearch" and "codesearch.google.com/" without also taking over requests for "http://www.google.com/".
Aha! Because of the restriction to match URLs on that host only.... in order to make ListenAndServe()
able to handle api.example.com
, you will need to introduce a new ServeMux(a HTTP request multiplexer) to enable the program to handle and resolve the sub domain.
This code example below is taken from another tutorial on how to use multiplexer, should be able to handle api.example.com
sub domain nicely.
package main
import "net/http"
type home struct{}
func (h home) ServeHTTP(w http.ResponseWriter, r *http.Request) {
w.Write([]byte("Hello, World!"))
}
type page struct {
body string
}
func (p page) ServeHTTP(w http.ResponseWriter, r *http.Request) {
// echo back the page first URI
w.Write([]byte(p.body))
}
// use map instead
type multiplexer map[string]http.Handler
func (m multiplexer) ServeHTTP(w http.ResponseWriter, r *http.Request) {
if handler, ok := m[r.RequestURI]; ok {
handler.ServeHTTP(w, r)
} else {
w.WriteHeader(http.StatusNotFound)
}
}
var mux = multiplexer{
"/": home{},
"/references/": page{"references"},
"/tutorials/": page{"tutorials"},
}
func main() {
http.ListenAndServe("api.example.com:8080", mux) // port 8080 is optional
}
Reference :
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
+11.4k SSL : The certificate is not trusted because no issuer chain was provided
+14.2k Golang : How to check if your program is running in a terminal
+15.1k Golang : Delete certain files in a directory
+35.8k Golang : How to split or chunking a file to smaller pieces?
+5.7k Golang : Detect variable or constant type
+9.2k Golang : Scramble and unscramble text message by randomly replacing words
+12.8k Golang : Calculate elapsed years or months since a date
+5.8k Fix ERROR 2003 (HY000): Can't connect to MySQL server on 'IP address' (111)
+16.3k Golang : File path independent of Operating System
+36.3k Golang : Display float in 2 decimal points and rounding up or down
+4.7k JQuery : Calling a function inside Jquery(document) block