go.chromium.org/luci@v0.0.0-20240309015107-7cdc2e660f33/server/analytics/gtag.go (about)

     1  // Copyright 2021 The LUCI Authors.
     2  //
     3  // Licensed under the Apache License, Version 2.0 (the "License");
     4  // you may not use this file except in compliance with the License.
     5  // You may obtain a copy of the License at
     6  //
     7  //      http://www.apache.org/licenses/LICENSE-2.0
     8  //
     9  // Unless required by applicable law or agreed to in writing, software
    10  // distributed under the License is distributed on an "AS IS" BASIS,
    11  // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    12  // See the License for the specific language governing permissions and
    13  // limitations under the License.
    14  
    15  package analytics
    16  
    17  // gtag.go has logic for generating Google Analytics 4 (gtag.js) snippet.
    18  
    19  import (
    20  	"fmt"
    21  	"html/template"
    22  	"regexp"
    23  )
    24  
    25  var rGA4Allowed = regexp.MustCompile(`^G-[A-Z0-9]+$`)
    26  
    27  // makeGTagSnippet returns an HTML snippet for Google Analytics 4.
    28  func makeGTagSnippet(measurementID string) template.HTML {
    29  	return template.HTML(
    30  		fmt.Sprintf(`
    31  			<!-- Global site tag (gtag.js) - Google Analytics -->
    32  			<script async src="https://www.googletagmanager.com/gtag/js?id=%s"></script>
    33  			<script>
    34  			window.dataLayer = window.dataLayer || [];
    35  			function gtag(){dataLayer.push(arguments);}
    36  			gtag('js', new Date());
    37  
    38  			gtag('config', '%s');
    39  			</script>`,
    40  			measurementID, measurementID,
    41  		),
    42  	)
    43  }