PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Wednesday, September 21, 2022

[FIXED] How to get "virtualhost" functionality in Go?

 September 21, 2022     go, virtualhost     No comments   

Issue

With Nginx/Django create virtualhosts is as easy as to write appropriate config.

For Go I found this https://codereview.appspot.com/4070043 and I understand that I have to use ServeMux but how to implement it?

I mean I must have 1 binary for all projects or I have to create some "router" server which will route requests depending on hostname? How to do it "Go"-way?


Solution

You are correct that you will use the ServeMux. The godoc for ServeMux has some detailed information about how to use it.

In the standard http package, there is the DefaultServeMux which can be manipulated using the top-level Handle functions. For example, a simple virtual host application might look like:

package main

import (
    "fmt"
    "net/http"
)

func main() {
    http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
        fmt.Fprintf(w, "Hello, world!")
    })
    http.HandleFunc("qa.example.com/", func(w http.ResponseWriter, r *http.Request) {
        fmt.Fprintf(w, "Hello, improved world!")
    })
    http.ListenAndServe(":8080", nil)
}

In this example, all requests to qa.example.com will hit the second handler, and all requests to other hosts will hit the first handler.



Answered By - Kyle Lemons
Answer Checked By - Candace Johnson (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing