I am writing a code which scans a test file and replaces the text with something else. Would like to replace same set of lines with different texts stacked one below the other. One option i found is using the tee function of ioreader, but is there a better way to achieve the same.
For instance, what i am trying to achieve is replacing the methodtype
substring in below piece of text with different strings like GET
, POST
, etc. To get the output as below:
TEXT:
router.Methods("methodtype").Path(templatepackagespec.MethodtypePath).Handler(kitHttp.NewServer(endpoints.FuncnameEndpoint
httptransport.EncodeResponse,
append(options, kitHttp.ServerBefore())...
OUTPUT:
router.Methods("GET").Path(templatepackagespec.MethodtypePath).Handler(kitHttp.NewServer(endpoints.FuncnameEndpoint
httptransport.EncodeResponse,
append(options, kitHttp.ServerBefore())...
router.Methods("PUT").Path(templatepackagespec.MethodtypePath).Handler(kitHttp.NewServer(endpoints.FuncnameEndpoint
httptransport.EncodeResponse,
append(options, kitHttp.ServerBefore())...
router.Methods("POST").Path(templatepackagespec.MethodtypePath).Handler(kitHttp.NewServer(endpoints.FuncnameEndpoint
httptransport.EncodeResponse,
append(options, kitHttp.ServerBefore())...
In order to replace text, you can use text/template instead of bufio:
Playground: https://play.golang.org/p/7HYBqxtJ3KB
package main
import (
"fmt"
"text/template"
"os"
)
type method struct {
MethodType string
}
func main() {
buf := `router.Methods("{{.MethodType}}").Path(templatepackagespec.MethodtypePath).Handler(kitHttp.NewServer(endpoints.FuncnameEndpoint
httptransport.EncodeResponse, append(options, kitHttp.ServerBefore())...
`
tmpl, err := template.New("test").Parse(buf)
if err != nil {
panic(err)
}
methods := []string{"GET", "PUT", "POST"}
for _, m := range methods {
err = tmpl.Execute(os.Stdout, method{MethodType: m})
if err != nil {
fmt.Println(err.Error())
}
}
}
Output:
router.Methods("GET").Path(templatepackagespec.MethodtypePath).Handler(kitHttp.NewServer(endpoints.FuncnameEndpoint
httptransport.EncodeResponse, append(options, kitHttp.ServerBefore())...
router.Methods("PUT").Path(templatepackagespec.MethodtypePath).Handler(kitHttp.NewServer(endpoints.FuncnameEndpoint
httptransport.EncodeResponse, append(options, kitHttp.ServerBefore())...
router.Methods("POST").Path(templatepackagespec.MethodtypePath).Handler(kitHttp.NewServer(endpoints.FuncnameEndpoint
httptransport.EncodeResponse, append(options, kitHttp.ServerBefore())...