add reactjs to a template in go

To add ReactJS to a template in Go, first, you need to create a route that will serve the HTML file containing your React components. Here is an example route handler:

main.go
func IndexHandler(w http.ResponseWriter, r *http.Request) {
    w.Header().Set("Content-Type", "text/html")

    // read the HTML file
    html, err := ioutil.ReadFile("index.html")
    if err != nil {
        http.Error(w, err.Error(), http.StatusInternalServerError)
        return
    }

    // write the HTML file to the response
    _, err = w.Write(html)
    if err != nil {
        http.Error(w, err.Error(), http.StatusInternalServerError)
        return
    }
}
471 chars
18 lines

This route handler reads the index.html file, and writes it to the response with an appropriate content-type header. Here's an example index.html file:

<!doctype html>
<html>
  <head>
    <meta charset="utf-8">
    <title>ReactApp</title>
  </head>
  <body>
    <div id="root"></div>

    <script src="https://cdn.jsdelivr.net/npm/react@17.0.1/umd/react.production.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/react-dom@17.0.1/umd/react-dom.production.min.js"></script>

    <script src="app.js"></script>
  </body>
</html>
391 chars
16 lines

This HTML file includes the react and react-dom libraries from a CDN, and a app.js file that contains your React components.

Here's an example app.js file that renders a simple React component:

const App = () => {
  return (
    <div>
      <h1>Hello, world!</h1>
      <p>This is a React component rendered in a Go template.</p>
    </div>
  );
};

ReactDOM.render(<App />, document.getElementById("root"));
215 chars
11 lines

This app.js file renders a div containing an h1 and a p tag. It then renders this component into the div with the id root.

With these files in place, you should be able to navigate to http://localhost:8000/ (assuming you're running your Go server on port 8000) and see your React component rendered in the Go template.

related categories

gistlibby LogSnag