Golang : Inject/embed Javascript before sending out to browser example
Problem:
You want to grab some Javascript code from other sources such as an external server or you simply want to separate the Javascript code from your Golang code instead of lumping them together.
Once you grabbed the Javascript code, you want to inject/embed in your HTML code before sending it out to the ResponseWriter/client/browser.
How to do that?
Solution:
Use http.Get()
to get JavaScript from another server/URL or use ioutil.ReadFile()
to get from file. Next, combine the Javascript code into HTML before writing to ResponseWriter.
Below is an example that you can test out on localhost.
Here you go!
package main
import (
"fmt"
"io/ioutil"
"net/http"
"os"
)
func SayHelloWorld(w http.ResponseWriter, r *http.Request) {
html := `<!DOCTYPE HTML><html><body>Hello World
`
response, err := http.Get("http://localhost:8080/js") // or some external sources
if err != nil {
fmt.Println(err)
os.Exit(1)
}
defer response.Body.Close()
javascript, err := ioutil.ReadAll(response.Body) //<--- here!
if err != nil {
fmt.Println(err)
os.Exit(1)
}
html = html + string(javascript)
html = html + `
</body></html>`
w.Write([]byte(html))
}
func InjectJavaScript(w http.ResponseWriter, r *http.Request) {
js := `<script type="text/javascript" charset="utf-8">
alert("View page source to see injected/embedded Javascript code!");
</script>`
w.Write([]byte(js))
}
func main() {
mux := http.NewServeMux()
mux.HandleFunc("/", SayHelloWorld)
mux.HandleFunc("/js", InjectJavaScript)
http.ListenAndServe(":8080", mux)
}
Hope this helps!
References:
https://www.socketloop.com/tutorials/golang-convert-http-response-body-to-string
https://www.socketloop.com/tutorials/golang-read-file-with-ioutil
https://www.socketloop.com/tutorials/golang-http-server-example
See also : Golang : Daemonizing a simple web server process example
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
+16.2k Golang : How to implement two-factor authentication?
+11.8k Golang : Decompress zlib file example
+7.4k Gogland : Where to put source code files in package directory for rookie
+14.6k Golang : Basic authentication with .htpasswd file
+5.2k Golang : Get S3 or CloudFront object or file information
+29.2k Golang : Login(Authenticate) with Facebook example
+9.5k Golang : ffmpeg with os/exec.Command() returns non-zero status
+41.2k Golang : Convert string to array/slice
+6.7k Golang : Fibonacci number generator examples
+13.5k Golang : Get dimension(width and height) of image file
+6.6k Golang : How to solve "too many .rsrc sections" error?
+21.1k Golang : How to read float value from standard input ?